package org.Lin.dao;

import org.Lin.model.FriendList;
import org.Lin.util.DatabaseUtil;

import java.sql.*;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

public class FriendListDAO {

    public void insert(FriendList friend) throws SQLException {
        String sql = "INSERT INTO FriendList(user1_id, user2_id, relation_status) VALUES (?, ?, ?)";
        try (Connection conn = DatabaseUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setInt(1, friend.getUser1Id());
            stmt.setInt(2, friend.getUser2Id());
            stmt.setString(3, friend.getRelationStatus());
            stmt.executeUpdate();
        }
    }

    public List<FriendList> findByUserId(int userId) throws SQLException {
        List<FriendList> friends = new ArrayList<>();
        String sql = "SELECT * FROM FriendList WHERE user1_id = ? OR user2_id = ?";
        try (Connection conn = DatabaseUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setInt(1, userId);
            stmt.setInt(2, userId);
            ResultSet rs = stmt.executeQuery();
            while (rs.next()) {
                friends.add(mapToFriendList(rs));
            }
        }
        return friends;
    }

    public void delete(int id) throws SQLException {
        String sql = "DELETE FROM FriendList WHERE ID = ?";
        try (Connection conn = DatabaseUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setInt(1, id);
            stmt.executeUpdate();
        }
    }

    private FriendList mapToFriendList(ResultSet rs) throws SQLException {
        FriendList fl = new FriendList();
        fl.setID(rs.getInt("ID"));
        fl.setUser1Id(rs.getInt("user1_id"));
        fl.setUser2Id(rs.getInt("user2_id"));
        fl.setRelationStatus(rs.getString("relation_status"));
        fl.setCreatedAt(rs.getObject("created_at", LocalDateTime.class));
        fl.setLastModified(rs.getObject("last_modified", LocalDateTime.class));
        return fl;
    }
}
